package cn.chencq.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 跨域处理
 * 
 * @author chencq
 * @email chenchaoqun@incar100.com
 * 
 */
public class CorsFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse hres = (HttpServletResponse) response;
		hres.setHeader("Access-Control-Allow-Origin", "*");// 指定允许其他域名访问
		hres.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");// 响应类型  
		hres.setHeader("Access-Control-Max-Age", "3600");
		hres.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, x-incar-request-id,x-incar-token,x-incar-request-moudle,x-incar-request-uri,x-incar-app-id, Accept");// 响应头设置  
		
		
		HttpServletRequest req = (HttpServletRequest) request;
		if("OPTIONS".equalsIgnoreCase(req.getMethod())){//浏览器ajax发起
			hres.setStatus(HttpServletResponse.SC_OK);
			return ;
		}
		
		chain.doFilter(request, hres);
	}

	@Override
	public void destroy() {
	}

}
